/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.admin.controller;

import com.bifrost.common.base.ServerResponse;
import com.bifrost.common.constant.SessionConstant;
import com.bifrost.common.util.HttpRequestUtils;
import com.bifrost.constant.Constant;
import com.bifrost.entity.MerchantStore;
import com.bifrost.entity.Permission;
import com.bifrost.entity.Role;
import com.bifrost.entity.User;
import com.bifrost.model.vo.PermissionVO;
import com.bifrost.model.vo.UserVO;
import com.bifrost.service.AdminUserService;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 *
 *后台系统登录相关接口
 *@author joewee
 *@version 1.0.0
 *@Date 2018/4/4 16:49
 */
@RestController
@RequestMapping("/admin")
@Api("登录相关接口")
public class AdminLoginController {
    @Autowired
    private AdminUserService adminUserService;

    //@PostMapping("/login")
    @RequestMapping("/login")
    @ApiOperation("登录")
    public ServerResponse login(String username, String password){
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(token);
        }catch (UnknownAccountException e) {
            return ServerResponse.createByErrorMsg(e.getMessage());
        }catch (IncorrectCredentialsException e) {
            return ServerResponse.createByErrorMsg(e.getMessage());
        }catch (LockedAccountException e) {
            return ServerResponse.createByErrorMsg(e.getMessage());
        }catch (AuthenticationException e) {
            return ServerResponse.createByErrorMsg("账户验证失败");
        }

        List<String> allPermissions = Lists.newArrayList();//存储全部权限
        Set<Permission> menuSet = new HashSet<Permission>();//获取当前用户能够访问的菜单(采用set，用于去重）
        User user = (User) subject.getPrincipal();
        Set<Role> roleSet = user.getRoles();
        if(CollectionUtils.isNotEmpty(roleSet)) {
            for(Role role : roleSet) {
                Set<Permission> permissionSet = role.getPermissions();
                if(CollectionUtils.isNotEmpty(permissionSet)) {
                    for(Permission permission : permissionSet) {
                        if(permission.getType() != Constant.Permission.PERMISSION_TYPE_BUTTON) {
                            menuSet.add(permission);
                        } else {
                            allPermissions.add(permission.getIdentifier());
                        }
                    }
                }
            }
        }
        List<PermissionVO> menuList = Lists.newArrayList();
        Iterator<Permission> iterator = menuSet.iterator();
        while(iterator.hasNext()) {
            Permission permission = iterator.next();
            PermissionVO permissionVO = PermissionVO.adapter(permission);
            menuList.add(permissionVO);
        }
        setRequestUserInfo(user);
        Map<String,Object> map = new HashMap<>();
        map.put("user", UserVO.adapter(user));
        map.put("menuList",menuList);
        map.put("permissions",allPermissions);
        return ServerResponse.createBySuccess(map);
    }

    private void setRequestUserInfo(User user) {
        HttpSession session = HttpRequestUtils.getCurrentRequest().getSession(true);
        Set<MerchantStore> merchantStores = user.getMerchantStores();
        if(user.getMerchantStore()!=null){
            session.setAttribute(SessionConstant.STORE_ID,user.getMerchantStore().getMerchantId());
        } else if(CollectionUtils.isNotEmpty(merchantStores)){
            session.setAttribute(SessionConstant.STORE_ID,merchantStores.iterator().next().getMerchantId());
        }
    }

    @PostMapping("/logout")
    @ApiOperation("退出")
    public ServerResponse logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.getSession();
        if(null != subject) {
            subject.logout();
            return ServerResponse.createBySuccessMsg("退出成功");
        }
        return ServerResponse.createByErrorMsg("没有登录");
    }
}
